﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GalaSoft.MvvmLight.Threading;
using Hammock;
using Hammock.Web;
using HtmlAgilityPack;
using _1906Ultras.Model;

namespace _1906Ultras.Helpers
{
    public class EventHelper : HelperBase
    {

        public EventHelper()
        {
            Authority = "http://www.1906ultras.com/";
            Request.Path = "events";
        }


        public void GetEvents(Action<ObservableCollection<Event>> callback)
        {
            BeginRequest((response) =>
            {
                try
                {
                    HtmlDocument htmDoc = new HtmlDocument();
                    htmDoc.LoadHtml(response);

                    var events = new ObservableCollection<Event>();

                    var node = htmDoc.DocumentNode.SelectNodes("//div[@class='entry']//h2").FindFirst("h2");
                    var e = new Event() {Name = node.InnerText};

                    while (node.NextSibling != null)
                    {
                        node = node.NextSibling;
                        if (node.Name == "h2")
                        {
                            events.Add(e);
                            e = new Event() {Name = node.InnerText};
                        }
                        else
                        {
                            e.Details += node.InnerText;
                            e.Details = Regex.Replace(e.Details, @"^\n", "");
                            e.Details = HttpUtility.HtmlDecode(Regex.Replace(e.Details, @"[\f\r\t\v]", ""));
                        }
                    }

                    e.Details = Regex.Replace(e.Details, @"^\n", "");
                    e.Details = HttpUtility.HtmlDecode(Regex.Replace(e.Details, @"[\f\r\t\v]", ""));
                    events.Add(e);


                    DispatcherHelper.CheckBeginInvokeOnUI(() =>
                                                              {
                                                                  GlobalLoading.Instance.IsLoading = false;
                                                                  callback(events);
                                                              });
                }
                catch (Exception e)
                {
                    ErrorCallbackInternal(e);
                }

            });
            
        }

    }
}
